// miniprogram/pages/merchant/apply/apply.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: app.globalData.userInfo,
    setting: app.globalData.setting,
    capsule: app.globalData.capsule,
    tip: '请勿上传非法图片',
    pr: {
      mch_id:'',
      cover: '',
      title: '',
      endDate: '',
      content: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'pr.mch_id':options.mch_id,
      userInfo: app.globalData.userInfo,
      setting: app.globalData.setting,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  chooseImg() {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (photo) {
        console.log(photo)
        var filePath = photo.tempFiles[0].path

        wx.getImageInfo({
          src: photo.tempFilePaths[0],
          success: function (res) {
            //---------利用canvas压缩图片--------------
            var ratio = 2;
            var canvasWidth = res.width //图片原始长宽
            var canvasHeight = res.height
            while (canvasWidth > 300 || canvasHeight > 300) { // 保证宽高在400以内
              canvasWidth = Math.trunc(res.width / ratio)
              canvasHeight = Math.trunc(res.height / ratio)
              ratio++;
            }
            that.setData({
              cWidth: canvasWidth,
              cHeight: canvasHeight
            })

            //----------绘制图形并取出图片路径--------------
            var ctx = wx.createCanvasContext('canvas', this)
            ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
            ctx.draw(false, setTimeout(function () {
                wx.canvasToTempFilePath({
                  canvasId: 'canvas',
                  fileType: 'jpg',
                  destWidth: canvasWidth,
                  destHeight: canvasHeight,
                  success: function (res) {
                    console.log('压缩后路径', res.tempFilePath) //最终图片路径
                    that.setData({
                      tip: '正在检测图片...',
                    })

                    wx.getFileSystemManager().readFile({
                      filePath: res.tempFilePath,
                      success: res => {
                        console.log(res.data)
                        wx.cloud.callFunction({
                          name: "promotion",
                          data: {
                            op: 'checkImg',
                            buffer: res.data
                          }
                        }).then(res => {
                          console.log(res)
                          if (res.result == 'pass') {
                            that.setData({
                              tip: '图片检测通过',
                            })
                            that.uploadCover(filePath)
                          } else {
                            that.setData({
                              tip: '重新选择图片',
                            })
                            wx.showModal({
                              content: '图片含有违法违规内容,请重新选择图片。请不要挑战内容审查，负向积分+1。',
                              confirmText: '重新选择',
                              // cancelText: '取消',
                              success(res) {
                                if (res.confirm) {
                                  that.chooseImg()
                                }
                              }
                            })
                          }
                        })
                      }
                    })
                  },
                  fail: function (res) {
                    console.log(res.errMsg)
                  }
                }, this)
              },
              100)) //留一定的时间绘制canvas
          }
        })
      }
    })

  },
  uploadCover(filePath) {
    // 上传图片
    this.setData({
      tip: '检测通过，正在上传...'
    })
    const cloudPath = 'promotion-cover/' + app.globalData.userInfo._openid + '-' + Math.random().toString(36).substr(2) + filePath.match(/\.[^.]+?$/)[0]
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res)
        this.setData({
          'pr.cover': res.fileID
        })
      }
    })
  },
  titleInput: function (e) {
    this.setData({
      'pr.title': e.detail.value
    })
  },
  dateChange(e) {
    this.setData({
      'pr.endDate': e.detail.value
    })
  },
  finish: function (e) {
    console.log("onfinish", e.detail.content);
    this.setData({
      'pr.content': e.detail.content
    })
    let pr = this.data.pr
    console.log(pr)
    if (!pr.title || !pr.cover || !pr.endDate) {
      wx.showToast({
        title: '活动封面、标题、截止日期不可为空',
        icon: 'none'
      })
      return false
    }

    wx.showLoading({
      title: '正在保存',
    })
    wx.cloud.callFunction({
      name: 'promotion',
      data: {
        op: 'apply',
        pr: pr
      },
      success: res => {
        wx.hideLoading()
        wx.showModal({
          content: '活动发布申请提交后，须经管理员审核，审核通过后才会对外展示。',
          confirmText: '明白了',
          showCancel: false,
         
          success(res) {
            if (res.confirm) {
             wx.navigateBack()
            }
          }
        })
      
      }
    })
  },
  apply() {
    this.selectComponent('#contentEditor').onFinish()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})